<template>
	<div class="device-list">
		<div class="device-list-container flex-container">
			<el-row class="search-row">
				<el-col :span="24">
					<el-form :inline="true" :model="searchForm" class="demo-form-inline">

						<el-form-item label="用户名">
							<el-select v-model="searchForm.user_id" filterable default-first-option clearable
									   class="form-control" placeholder="请选择">
								<el-option
										v-for="item in userList"
										:key="item.id"
										:label="item.username"
										:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="分组">
							<el-select v-model="searchForm.group_id" filterable default-first-option clearable
									   class="form-control" placeholder="请选择">
								<el-option
										v-for="item in groupList"
										:key="item.id"
										:label="item.name"
										:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="车位号">
							<el-input v-model="searchForm.park_no" placeholder=""></el-input>
						</el-form-item>
						<el-form-item label="安装地址">
							<el-input v-model="searchForm.address" placeholder=""></el-input>
						</el-form-item>
						<el-form-item class="pull-right">
							<el-button type="primary" @click="clearSearchOption">清空</el-button>
							<el-button type="success" @click="getDeviceList">查询</el-button>
						</el-form-item>
					</el-form>
				</el-col>
			</el-row>

			<div class="device-list-table">
				<!--<div class="all-select-holder">-->
					<!--<el-checkbox v-model="allSelected" @change="selectAll"></el-checkbox>-->
				<!--</div>-->
				<el-table :data="deviceList" border :row-class-name="rowClass"
						  ref="multipleTable" @selection-change="handleSelectionChange" @sort-change="sortChange">
					<!--<el-table-column  width="55" fixed="left">-->
						<!--<template slot-scope="scope">-->
							<!--<el-checkbox v-model="scope.row.selected" @change="selectItem(scope.row)">-->
							<!--</el-checkbox>-->
						<!--</template>-->
					<!--</el-table-column>-->
					<el-table-column label="Imei" min-width="180" prop="device_id" sortable="custom">
						<template slot-scope="scope">
							<router-link target="_blank" class="link"
										 :to="{path: '/device/detail', query: {id: scope.row.id, space: scope.row.space, device_id: scope.row.device_id}}">
								{{ scope.row.device_id }}
							</router-link>
						</template>
					</el-table-column>
					<el-table-column label="设备Id" min-width="180" prop="device_id" sortable="custom">
						<template slot-scope="scope">
							{{ scope.row.outer_device_id }}
						</template>
					</el-table-column>
					<el-table-column label="是否离线" min-width="100">
						<template slot-scope="scope">
							{{scope.row.last_active_time | isOff}}
						</template>
					</el-table-column>
					<el-table-column label="最后活动时间" min-width="170" sortable="custom" prop="active_time">
						<template slot-scope="scope">
							{{scope.row.last_active_time | timeFormat}}
						</template>
					</el-table-column>
					<el-table-column label="创建时间" min-width="170" sortable="custom"  prop="create_time">
						<template slot-scope="scope">
							{{scope.row.create_time | timeFormat}}
						</template>
					</el-table-column>
					<el-table-column label="车位号" min-width="120" prop="park_no" sortable="custom">
						<template slot-scope="scope">
							{{scope.row.park_no || '--'}}
						</template>
					</el-table-column>
					<el-table-column label="电池电压" min-width="170" sortable="custom" prop="battery_voltage">
					</el-table-column>
					<el-table-column label="信号强度" min-width="170" sortable="custom"  prop="rssi">
					</el-table-column>

					<el-table-column label="安装地址" min-width="170" sortable="custom"  prop="address">
						<template slot-scope="scope">
							{{scope.row.address}}
						</template>
					</el-table-column>
					<el-table-column label="车位状态" min-width="150" sortable="custom" prop="status">
						<template slot-scope="scope">
							{{scope.row.p1 | parkStateType}}
						</template>
					</el-table-column>
					<el-table-column label="用户名" min-width="150" prop="user_id" sortable="custom">
						<template slot-scope="scope">
							{{scope.row.user ? scope.row.user.username : '-'}}
						</template>
					</el-table-column>
					<el-table-column prop="group_name" label="分组" width="150"></el-table-column>

					<el-table-column label="操作" fixed="right" width="200">
						<template slot-scope="scope">
							<el-button type="success outline" size="mini"
									   @click="handleEditBaseInfo(scope.$index, scope.row)">
								编辑
							</el-button>
							<el-button type="success outline" size="mini"
									   @click="handleEdit(scope.$index, scope.row)">
								分配
							</el-button>
							<el-button size="mini" type="danger outline"
									   @click="handleDelete(scope.$index, scope.row)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<div class="flex-footer h-80">
				<div class="flex-footer-content">
					<el-row>
						<el-col :span="8" class="pt-6">
							<el-button type="success" @click="handleAddDevice">添加设备</el-button>
						</el-col>
						<el-col :span="16" class="text-center" v-if="total > 0">
							<el-pagination
									@current-change="pageChange"
									:current-page="currentPage"
									:page-size="pageSize"
									layout="total, prev, pager, next, jumper"
									:total="total">
							</el-pagination>
						</el-col>
						<!--<el-col :span="8" class="text-center" v-if="total > 0"></el-col>-->
					</el-row>
				</div>
			</div>
		</div>

		<!--编辑弹窗-->
		<el-dialog title="更新到指定账户" custom-class="edit-dialog" :visible.sync="editModalVisible"  @close="dialogCloseCallback">
			<el-form :label-position="'left'" label-width="110px" ref="userForm" :model="userForm">
				<el-form-item label="当前用户名:" prop="current_user_name">
					{{userForm.current_user_name}}
				</el-form-item>
				<el-form-item label="当前分组:" prop="current_group_name">
					{{userForm.current_group_name}}
				</el-form-item>
				<el-form-item label="目标用户名" prop="target_user_id">
					<el-select v-model="userForm.target_user_id" filterable default-first-option clearable
							   class="form-control" placeholder="请选择">
						<el-option
								v-for="item in userList"
								:key="item.id"
								:label="item.username"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="目标分组">
					<el-select v-model="userForm.target_group_id" filterable default-first-option clearable
							   class="form-control" placeholder="请选择">
						<el-option
								v-for="item in userGroupList"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="success" @click="saveDevice('userForm')">确认更新</el-button>
			</div>
		</el-dialog>

		<!--更新基本信息弹窗-->
		<el-dialog title="更新基本信息" custom-class="edit-dialog" :visible.sync="baseInfoModalVisible"  @close="baseInfoDialogCloseCallback">
			<el-form :label-position="'left'" label-width="110px" ref="baseInfoForm" :model="baseInfoForm">
				<!--<el-form-item label="当前用户名:" prop="current_user_name">-->
				<!--{{userForm.current_user_name}}-->
				<!--</el-form-item>-->
				<el-form-item label="车位号:" prop="park_no">
					<el-input placeholder="请填写车位号" v-model="baseInfoForm.park_no"></el-input>
				</el-form-item>
				<el-form-item label="安装地址:" prop="address">
					<el-input placeholder="请填写安装地址" v-model="baseInfoForm.address"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="success" @click="saveBaseInfo('baseInfoForm')">确认更新</el-button>
			</div>
		</el-dialog>

		<!--删除弹窗-->
		<el-dialog title="删除设备" custom-class="edit-dialog" :visible.sync="deleteModalVisible" @close="deleteDialogCloseCallback">
			<p style="padding: 20px 0;">提示：必须填入密码才能删除该设备</p>
			<el-form :label-position="'left'" label-width="110px" ref="deleteForm" :model="deleteForm">
				<el-form-item label="密码:" prop="password" :rules="[{ required: true, message: '密码不能为空'}]">
					<el-input type="password" placeholder="请填写密码" v-model="deleteForm.password"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="success" @click="deleteDevice('deleteForm')">确认</el-button>
			</div>
		</el-dialog>

		<!--设置弹窗-->
		<el-dialog title="设置" custom-class="edit-dialog" :visible.sync="settingModalVisible"  @close="settingDialogCloseCallback">
			<el-form :label-position="'left'" label-width="110px" ref="settingForm" :model="settingForm">
				<el-form-item label="有车决策时间:" prop="hasCarTime">
					<el-input placeholder="4～30s" v-model="settingForm.hasCarTime"></el-input>
				</el-form-item>
				<el-form-item label="无车决策时间:" prop="noCarTime">
					<el-input placeholder="4～30s" v-model="settingForm.noCarTime"></el-input>
				</el-form-item>
				<el-form-item label="地磁校准">
					<el-radio-group v-model="settingForm.calibration">
						<el-radio :label="1">是</el-radio>
						<el-radio :label="0">否</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="灵敏度" prop="sensitivity">
					<el-select v-model="settingForm.sensitivity" filterable default-first-option clearable
							   class="form-control" placeholder="请选择">
						<el-option
								v-for="item in sensitivityList"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="心跳频率">
					<el-select v-model="settingForm.heartbeatFrequency" filterable default-first-option clearable
							   class="form-control" placeholder="请选择">
						<el-option
								v-for="item in heartbeatFrequencyList"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="基值跟踪">
					<el-select v-model="settingForm.baseValue" filterable default-first-option clearable
							   class="form-control" placeholder="请选择">
						<el-option
								v-for="item in baseValueList"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="success" @click="saveSetting('settingForm')">确认</el-button>
			</div>
		</el-dialog>

		<!--编辑弹窗-->
		<el-dialog title="添加设备" custom-class="edit-dialog" :visible.sync="addDeviceModalVisible"
				   @close="addDeviceDialogCloseCallback">
			<el-form :label-position="'left'" label-width="110px" ref="deviceForm" :model="deviceForm">
				<el-form-item label="设备ID:" prop="device_id"
							  :rules="[{ required: true, message: '设备ID不能为空'}]">
					<el-input v-model="deviceForm.device_id"></el-input>
				</el-form-item>
				<el-form-item label="用户名">
					<el-select v-model="deviceForm.user_id" filterable default-first-option clearable
							   class="form-control" placeholder="请选择">
						<el-option
								v-for="item in userList"
								:key="item.id"
								:label="item.username"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="分组">
					<el-select v-model="deviceForm.group_id" filterable default-first-option clearable
							   class="form-control" placeholder="请选择">
						<el-option
								v-for="item in groupList"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="success" @click="addDevice('deviceForm')">确认添加</el-button>
			</div>
		</el-dialog>


		<el-dialog title="导入失败设备列表" custom-class="edit-dialog" :visible.sync="importModalVisible">
			<el-table :data="processFailList">
				<el-table-column property="id" label="ID" width="80"></el-table-column>
				<el-table-column property="device_id" label="设备ID"></el-table-column>
				<el-table-column property="reason" label="原因"></el-table-column>
			</el-table>

			<div class="flex-footer">
				<div class="flex-footer-content">
					<el-row>
						<el-col :span="24" class="text-center" v-if="failTotal > 0">
							<el-pagination
									@current-change="failPageChange"
									:current-page="failCurrentPage"
									:page-size="failPageSize"
									layout="total, prev, pager, next"
									:total="failTotal">
							</el-pagination>
						</el-col>
					</el-row>
				</div>
			</div>
		</el-dialog>

		<!--批量重启-->
		<el-dialog title="设备列表" custom-class="" :visible.sync="batchDialogVisible">
			<div style="max-height: 400px; overflow: auto">
				<p v-if="selectIdList.length > 0" style="font-size: 14px; color: #212121; font-weight: bold">设备Id :</p>
				<label style="display: inline-block; width: 120px; line-height: 20px; margin-top: 4px" v-for="item in selectIdList">
					{{item}}
				</label>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="batchDialogVisible = false">取消</el-button>
                 <el-button type="primary" @click="batchReboot">重启</el-button>
            </span>
		</el-dialog>

		<!--批量设置-->
		<el-dialog title="批量设置" custom-class="edit-dialog" :visible.sync="batchSetDialogVisible"
		           @close="setConfigDialogCloseCallback">
			<div style="max-height: 200px; overflow: auto">
				<p v-if="selectIdList.length > 0" style="font-size: 14px; color: #212121; font-weight: bold">设备Id :</p>
				<label style="display: inline-block; width: 120px; line-height: 20px; margin-top: 4px" v-for="item in selectIdList">
					{{item}}
				</label>
			</div>
			<div class="clear-20"></div>
			<el-form :label-position="'left'" ref="configForm" label-width="120px" :model="configForm">
				<el-form-item label="决策开启时间:" prop="on_decision_time"
				              :rules="[{ required: true, message: '决策开启时间不能为空'}]">
					<el-input v-model="configForm.on_decision_time"></el-input>
				</el-form-item>
				<el-form-item label="决策关闭时间:" prop="off_decision_time"
				              :rules="[{ required: true, message: '决策关闭时间不能为空'}]">
					<el-input v-model="configForm.off_decision_time"></el-input>
				</el-form-item>
				<el-form-item label="灵敏度:" prop="sensitivity" :rules="[{ required: true, message: '灵敏度不能为空'}]">
					<el-input v-model="configForm.sensitivity"></el-input>
				</el-form-item>
				<el-form-item label="心跳时间:" prop="heartbeat_time" :rules="[{ required: true, message: '心跳时间不能为空'}]">
					<el-input v-model="configForm.heartbeat_time"></el-input>
				</el-form-item>
				<el-form-item label="环境跟踪值:" prop="environment_track_time" :rules="[{ required: true, message: '环境跟踪值'}]">
					<el-input-number v-model="configForm.environment_track_time"></el-input-number>
				</el-form-item>
				<el-form-item label="频点:" prop="frequency_point" :rules="[{ required: true, message: '频点'}]">
					<el-input-number v-model="configForm.frequency_point"></el-input-number>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="success" @click="writeDataSetConfig">设置</el-button>
			</div>
		</el-dialog>

		<!--数据弹窗-->
		<el-dialog title="最新数据" :visible.sync="frameDialogVisible" custom-class="frame-dialog" width="900px">
			<div class="content"><pre class="consolas">{{ frame }}</pre></div>
		</el-dialog>
	</div>
</template>

<script type="text/ecmascript-6">

	import Core from 'core/core'

	export default {
		data() {
			return {
			    space: "20013",
				Core: Core,
				searchForm: {
					device_id: '',
					user_id: '',
					group_id: '',
					park_no: '',
					address: ''
				},
				userList: [],
				groupList: [],
				userGroupList: [],
				deviceList: [],
				// 分页配置
				currentPage: 1,
				total: 0,
				pageSize: 20,

				editModalVisible: false,
				userForm: {
					device_id: '',
					current_user_name: '',
					current_group_name: '',
					target_user_id: '',
					target_group_id: ''
				},
				deleteModalVisible: false,
				deleteForm: {
					device_id: '',
					password: ''
				},
				settingModalVisible: false,
				settingForm: {
					hasCarTime: '',
					noCarTime: '',
					calibration: 0,
					sensitivity: '',
					heartbeatFrequency: '',
					baseValue: ''
				},
				sensitivityList: [
					{ id: '-2', name: '最弱' },
					{ id: '-1', name: '较弱' },
					{ id: '0', name: '中性' },
					{ id: '1', name: '增强' },
					{ id: '2', name: '最强' },
				],
				heartbeatFrequencyList: [
					{ id: 1, name: '快速' },
					{ id: 2, name: '中速' },
					{ id: 3, name: '慢速' }
				],
				baseValueList: [
					{ id: 1, name: '快速' },
					{ id: 2, name: '中速' },
					{ id: 3, name: '慢速' }
				],
				multipleSelection: [],

				addDeviceModalVisible: false,
				deviceForm: {
					device_id: '',
					user_id: '',
					group_id: ''
				},
				upload: {
					url: Core.Const.NET.UPLOAD_DEVICE_URL,
					data: {
						token: Core.Data.getToken(),
						space: "20013"
					}
				},
				importModalVisible: false,
				failList: [],
				processFailList: [],

				// 分页配置
				failCurrentPage: 1,
				failTotal: 0,
				failPageSize: 10,

				baseInfoModalVisible: false,
				baseInfoForm: {
					id: '',
					park_no: '',
					address: ''
				},

				selectIdList: [],
				allSelected: false,
				batchDialogVisible: false,
				batchSetDialogVisible: false,
				configForm: {
					on_decision_time: '',
					off_decision_time: '',
					sensitivity: '',
					heartbeat_time: '',
                    environment_track_time: '',
                    frequency_point: '',
				},

				//帧数据
				frame: '',
				frameDialogVisible: false,

				sortType: 1,
			}
		},
		mounted: function () {
			let url = window.location.href;

			if (url.indexOf("test.ajaiot.com") > -1 || url.indexOf("test.fegiot.com") > -1) {
				this.upload.url = Core.Const.NET.UPLOAD_TEST_DEVICE_URL;
			} else {
				this.upload.url = Core.Const.NET.UPLOAD_DEVICE_URL;
			}
			this.getUserList();
			this.getDeviceList();
		},
		watch: {
			'searchForm.user_id': 'getGroupList',
			'userForm.target_user_id': 'getUserGroupList',
			'deviceForm.user_id': 'getGroupListForDevice',
		},
		methods: {
			rowClass: function (row, index) {
				if (row.p1 === "1") {
					return 'success-row';
				} else {
					return 'warning-row';
				}
			},
			getUserList() {
				Core.Api.User.allList()
					.then(res => {
						this.userList = res.user_list;
					})
					.catch(err => {
						this.$message.error(err.message);
					});
			},
			getGroupList() {
				Core.Api.Group.listForAdmin(this.searchForm.user_id, 0)
					.then(res => {
						this.searchForm.group_id = '';
						this.groupList = res.group_list;
					})
					.catch(err => {
						this.$message.error(err.message);
					});
			},
			getGroupListForDevice() {
				Core.Api.Group.listForAdmin(this.deviceForm.user_id, 0)
					.then(res => {
						this.deviceForm.group_id = '';
						this.groupList = res.group_list;
					})
					.catch(err => {
						this.$message.error(err.message);
					});
			},
			getUserGroupList() {
				Core.Api.Group.listForAdmin(this.userForm.target_user_id, 0)
					.then(res => {
						this.userGroupList = res.group_list;
					})
					.catch(err => {
						this.$message.error(err.message);
					});
			},
			getDeviceList() {
			    console.log(this.searchForm);
				Core.Api.Device.getDeviceList(this.space, this.searchForm.device_id, this.searchForm.user_id, this.searchForm.group_id,
					this.searchForm.address, this.searchForm.park_no, this.currentPage, this.sortType).then(res => {
						let deviceList = res.device_list;
						let $this = this;
						deviceList.forEach(function (v) {
							v.selected = ($this.selectIdList.indexOf(v.device_id) > -1);
							let data = v.data;
							v.last_frame = {time: 0};
							v.conn_signal_strength = '-';
							if (data && data.last_frame_0101) {
								if (v.last_frame.time < data.last_frame_0101.time) {
									v.last_frame = data.last_frame_0101;
								}
								if (data.last_frame_0101.data) {
									data.last_frame_0101.data = JSON.parse(data.last_frame_0101.data)
								}
							}
							if (data && data.last_frame_0102) {
								if (v.last_frame.time < data.last_frame_0102.time) {
									v.last_frame = data.last_frame_0102;
								}
								if (data.last_frame_0102.data) {
									v.conn_signal_strength = data.last_frame_0102.conn_signal_strength;
									data.last_frame_0102.data = JSON.parse(data.last_frame_0102.data)
								}
							}
							if (data && data.last_frame_0206) {
								if (v.last_frame.time < data.last_frame_0206.time) {
									v.last_frame = data.last_frame_0206;
								}
								if (data.last_frame_0206.data) {
									data.last_frame_0206.data = JSON.parse(data.last_frame_0206.data)
								}
							}
						});
						let notSelectedList  = deviceList.filter(i => {
							return !i.selected
						});
						this.deviceList = deviceList;
						this.total = res.count;
						this.allSelected = !(notSelectedList.length > 0);
				});
			},
			pageChange(val) {
				this.currentPage = val;
				this.getDeviceList();
			},
			handleEdit(index, row) {
				this.userForm.id = row.id;
                this.userForm.device_id = row.device_id;
				this.userForm.current_user_name = row.user.username;
				this.userForm.current_group_name = row.group_name;
				this.editModalVisible = true;
			},
			handleDelete(index, row) {
				this.deleteModalVisible = true;
				this.deleteForm.device_id = row.id;
			},
			clearSearchOption() {
				this.searchForm = {
					device_id: '',
					user_id: '',
					group_id: '',
					park_no: '',
					address: ''
				};
				this.getDeviceList();
			},
			saveDevice(formName) {
				this.$refs[formName].validate(valid => {
					if (!valid) return false;

					Core.Api.Device.saveTargetUser(
						this.userForm.id,
						this.userForm.target_user_id,
						this.userForm.target_group_id
					)
						.then(res => {
							this.$message.success("更新成功");
							this.editModalVisible = false;

							this.userForm = {
								device_id: '',
								current_user_name: '',
								current_group_name: '',
								target_user_id: '',
								target_group_id: ''
							};
							this.getDeviceList();
						})
						.catch(err => {
							this.$message.error(err.message);
						})
				});
			},
			deleteDevice(formName) {
				this.$refs[formName].validate(valid => {
					if (!valid) return false;

					let password = this.deleteForm.password.trim();
					if (password === Core.Const.NET.DEVICE_DELETE_PASSWORD) {
					    // return;
						Core.Api.Device.delete(this.deleteForm.device_id)
							.then(() => {
								this.$message({
									type: 'success',
									message: '删除成功!'
								});

								this.getDeviceList();
								this.deleteModalVisible = false;
							})
							.catch(() => {
							});
					} else {
						this.$message({
							type: 'error',
							message: '密码错误, 请重试!'
						});
					}
				});
			},
			dialogCloseCallback() {
				this.userForm = {
					device_id: '',
					current_user_name: '',
					current_group_name: '',
					target_user_id: '',
					target_group_id: ''
				};
			},
			deleteDialogCloseCallback() {
				this.deleteForm = {
					device_id: '',
					password: ''
				};
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			settingDialogCloseCallback() {
				this.settingForm = {
					hasCarTime: '',
					noCarTime: '',
					calibration: 0,
					sensitivity: '',
					heartbeatFrequency: '',
					baseValue: ''
				};
				this.$refs.multipleTable.clearSelection()
			},
			toggleSelection(row) {
				this.settingModalVisible = true;
				this.$refs.multipleTable.toggleRowSelection(row);
			},
			toggleAllSelection() {
				this.deviceList.forEach(row => {
					this.$refs.multipleTable.toggleRowSelection(row);
				});
				this.settingModalVisible = true;
			},
			saveSetting(formName) {
				this.$refs[formName].validate(valid => {
					if (!valid) return false;

					this.settingModalVisible = false;
				});
			},
			handleAddDevice() {
				this.addDeviceModalVisible = true;
			},
			addDeviceDialogCloseCallback() {
				this.deviceForm = {
					device_id: '',
					user_id: '',
					group_id: ''
				};
				this.addDeviceModalVisible = false;
			},
			addDevice(formName) {
				this.$refs[formName].validate(valid => {
					if (!valid) return false;

					let deviceId = this.deviceForm.device_id;
					let userId = this.deviceForm.user_id;
					let groupId = this.deviceForm.group_id;

					Core.Api.Device.saveFor20013ByAdmin(0, "20013", deviceId, userId, groupId)
						.then(res => {
							this.$message.success("添加成功");
							this.addDeviceModalVisible = false;

							this.deviceForm = {
								device_id: '',
								user_id: '',
								group_id: ''
							};
							this.getDeviceList();
						})
						.catch(err => {
							this.$message.error(err.message);
						})
				});
			},
			handleUploadDevice(res) {
				this.failList = res.data.fail_list;
				this.failTotal = this.failList.length;

				if (this.failList.length <= 0) {
					this.$message({
						message: '上传成功',
						type: 'success',
					});
					this.importModalVisible = false;
				} else {
					this.getFailList();
					this.importModalVisible = true;
				}

				this.getDeviceList();
			},
			failPageChange(val) {
				this.failCurrentPage = val;
				this.getFailList();
			},
			getFailList() {
				this.processFailList = this.failList.slice((this.failCurrentPage - 1) * this.failPageSize, this.failCurrentPage * this.failPageSize);
			},


			handleEditBaseInfo(index, row) {
				this.baseInfoForm.id = row.id;
				this.baseInfoForm.park_no = row.park_no;
				this.baseInfoForm.address = row.address;
				this.baseInfoModalVisible = true;
			},
			baseInfoDialogCloseCallback() {
				this.baseInfoForm = {
					id: '',
					park_no: '',
					address: ''
				};
			},
			saveBaseInfo(formName) {
				this.$refs[formName].validate(valid => {
					if (!valid) return false;

					Core.Api.Device.saveBaseInfo(
						this.baseInfoForm.id,
						this.baseInfoForm.park_no,
						this.baseInfoForm.address
					)
						.then(res => {
							this.$message.success("更新成功");
							this.baseInfoModalVisible = false;

							this.baseInfoForm = {
								id: '',
								park_no: '',
								address: ''
							};
							this.getDeviceList();
						})
						.catch(err => {
							this.$message.error(err.message);
						})
				});
			},

			getIdList(list) {
				let idList = [];
				list.forEach(item => {
					idList.push(item.device_id);
				})
				return idList;
			},

			selectAll () {
				let idList = this.getIdList(this.deviceList);
				if (this.allSelected) {
					this.deviceList.forEach(v => {
						v.selected = this.allSelected
					})

					idList.forEach(v => {
						if (this.selectIdList.indexOf(v) < 0) {
							this.selectIdList.push(v);
						}
					})
				} else {
					this.deviceList.forEach(v => {
						v.selected = this.allSelected;
					});
					idList.forEach(v => {
						for(let i = 0; i < this.selectIdList.length;i++){
							if (this.selectIdList[i] === v) {
								this.selectIdList.splice(i, 1);
								break;
							}
						}
					})
				}
			},

			selectItem (item) {
				if (item.selected) {
					this.selectIdList.push(item.device_id);
				} else {
					this.selectIdList.forEach((v, i) => {
						if (v === item.device_id) {
							this.selectIdList.splice(i, 1);
						}
					})
				}
				let notSelectedList  = this.deviceList.filter(i => {
					return !i.selected
				});
				this.allSelected = !(notSelectedList.length > 0);
			},

			clearAllSelect() {
				this.selectIdList = [];
				this.selectIdList.length = 0;
				this.allSelected = false
				this.deviceList.forEach(i => {
					i.selected = false;
				} )
			},


			batchReboot() {
				let idList = this.selectIdList.join(',');
				Core.Api.Fengine.P20013BatchReboot(idList).then(res => {
					this.$message.success('重启成功');
					this.batchDialogVisible = false;
				}).catch(err => {
					console.log(err)
				})
			},

			showBatchDialog(type) {
				if (this.selectIdList.length <= 0) {
					this.$message("未选中任何设备");
					return;
				}
				switch (type) {
					case 'restart':
						this.batchDialogVisible = true;
						break;
					case 'setting':
						this.batchSetDialogVisible = true;
						break;
				}
			},

			setConfigDialogCloseCallback() {
				this.configForm = {
					on_decision_time: '',
					off_decision_time: '',
					sensitivity: '',
					heartbeat_time: '',
                    environment_track_time: '',
                    frequency_point: ''
				};
			},

			writeDataSetConfig() {
				console.log('tap batch setting');
				this.$refs['configForm'].validate((valid) => {
					if (!valid)
						return false;
					let idList = this.selectIdList.join(',');
					Core.Api.Fengine.P20013BatchSetConfig(idList,
						this.configForm.on_decision_time,
						this.configForm.off_decision_time,
						this.configForm.sensitivity,
						this.configForm.heartbeat_time,
                        this.configForm.environment_track_time,
                        this.configForm.frequency_point)
						.then(res => {
							this.canOperate = true;
							this.$message.success("操作成功");
							this.batchSetDialogVisible = false;
						});
				});
			},

			//frame dialog
			showFrameDialog(device) {
				this.frame = {
					dataFrame: '',
					heartFrame: '',
				};
				this.getFrameData(device);
			},

			getFrameData(device) {
				let deviceId = device.device_id;
				let space = device.space;

				let a = Core.Api.Frame.getFrameListForSpace(deviceId, space, 1, 1).then(res => {
					let frameList = res.frame_list;
					this.frame["dataFrame"] = frameList[0];
				});

				let b = Core.Api.Frame.getFrameListForSpace(deviceId, space, 2, 1).then(res => {
					let frameList = res.frame_list;
					this.frame["heartFrame"] = frameList[0];
				});
				let $this = this
				Promise.all([a, b]).then(function(values) {
					$this.frameDialogVisible = true;
				});
			},

            sortChange(sortItem) {
                let prop = sortItem.prop;
                let order = sortItem.order;
                this.sortType = Core.Util.sortType(prop, order);
                this.getDeviceList();
            },
		}
	}
</script>

<style scoped lang="scss">
	.device-list {
		height: 100%;
		.device-list-container {
			height: 100%;
			.search-row {
				margin: 0;
				padding: 15px 30px;
				background: #fff;
				.el-form--inline .el-form-item {
					margin-bottom: 0;
				}
				.el-form-item__label {
					padding-right: 10px;
					font-size: 12px;
				}
				.el-form-item__content {
					.el-input {
						width: 175px;
					}
				}
			}

			.device-list-table {
				padding: 20px 0;
				background: #ffffff;
				position: relative;
				flex: 1;
				overflow: auto;
				.all-select-holder {
					line-height: 30px;
					position: absolute;
					left: 10px;
					z-index: 10;
				}
			}
			.flex-footer {
				border-top: 1px solid #E0E7EF;
			}
			.flex-footer.h-80 {
				height: 80px;
			}

		}

		a.success {
			display: inline-block;
			color: #fff;
			background-color: #03CC75;
			border-color: #03CC75;
			line-height: 1;
			white-space: nowrap;
			cursor: pointer;
			-webkit-appearance: none;
			text-align: center;
			box-sizing: border-box;
			outline: none;
			-moz-user-select: none;
			-webkit-user-select: none;
			-ms-user-select: none;
			padding: 7px 16px;
			font-size: 12px;
			border-radius: 4px;
			margin: 0 10px;
		}

		.upload-device {
			display: inline-block;
		}
	}
</style>
